import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { db } from '@/lib/db';

// 安全的JSON解析函数
const safeJsonParse = (text: string) => {
  try {
    return JSON.parse(text);
  } catch (e) {
    console.error('JSON解析失败:', e);
    return null;
  }
};

// GET /api/users/me - 获取当前登录用户的信息
export async function GET(req: NextRequest) {
  try {
    // 获取会话信息
    const session = await auth();
    
    if (!session || !session.user?.email) {
      return NextResponse.json(
        { error: '用户未登录' },
        { status: 401 }
      );
    }
    
    // 从数据库获取用户信息
    const user = await db.user.findUnique({
      where: { email: session.user.email },
      include: {
        profile: true,
        settings: true,
        projects: {
          include: {
            project: true
          }
        }
      }
    });
    
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }
    
    // 确保安全返回，避免序列化问题
    const safeUser = {
      id: user.id,
      name: user.name,
      email: user.email,
      role: user.role,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt,
      profile: user.profile ? {
        id: user.profile.id,
        bio: user.profile.bio,
        avatar: user.profile.avatar,
        location: user.profile.location,
        company: user.profile.company,
        website: user.profile.website,
        skills: user.profile.skills,
        userId: user.profile.userId,
        createdAt: user.profile.createdAt,
        updatedAt: user.profile.updatedAt
      } : null,
      settings: user.settings ? {
        id: user.settings.id,
        theme: user.settings.theme,
        language: user.settings.language,
        notifications: user.settings.notifications,
        userId: user.settings.userId
      } : null,
      projects: user.projects.map(membership => ({
        id: membership.project.id,
        name: membership.project.name,
        description: membership.project.description,
        role: membership.role,
        status: membership.project.status,
        createdAt: membership.project.createdAt
      }))
    };
    
    // 直接返回对象，让NextResponse.json处理序列化
    return NextResponse.json(safeUser);
    
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return NextResponse.json(
      { error: '获取用户信息失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
} 